<?php

namespace app\controller\admin\map;

use app\model\admin\calendar\CalendarContent;
use app\model\admin\map\MapBoard;
use app\model\admin\map\MapBoardContent;
use app\model\admin\map\MapContent;
use app\model\admin\map\MapContentLabel;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\map
 */
class Board extends Backend
{
    protected $model;
    public $orderRule = ['sort'=>'ASC', 'id' => 'DESC'];
    protected $noNeedAuth = ['index', 'info'];
    public function initialize()
    {
        $this->model = new MapBoard();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //查看详情
    public function info()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        return $this->success('获取成功', $info);
    }

    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->withCount("content")->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());
        if(!$this->request->param("game_id")){
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        try {
            $data = [
                'relation_id' => $gameId,
                'name' => $post['name'],
                'sort' => $post['sort'],
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
                'status' =>2,
            ];
            Db::startTrans();
            $insertId = $this->model->insertGetId($data);
            if ($insertId) {
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = CommonFun::filterPostData($this->request->post());
        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::roolback();
                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //设置排序
    public function setStatus()
    {
        $id       = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['status'] = $fieldVal;
        $info = $this->model->where('id',$id)->find();
        if($info){
            if( $update['status']==1){
                $count = $this->model->where("relation_id",$info->relation_id)->where("status",1)->count();
                if($count>3){
                    return $this->error('上架榜单最多不能超过4个');
                }
            }
        }
        try {
            if($isRecycle) {
                $updateRes = $this->model->onlyTrashed()->where('id', '=', $id)->update($update);
            } else {
                $updateRes = $this->model->where('id', '=', $id)->update($update);
            }

            if ($updateRes) {
                $this->clearCache();
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    /**
     * 导入条数
     * @return false|string|\think\response\Json
     */
    public function import(){
        $file = $this->request->file("file");
        $game_id  = $this->request->post("game_id");
        $mapContentIds = (new MapContent())->where('relation_id',$game_id)->where("status",1)->column("id");
        $mapBoardIds = (new MapBoard())->where('relation_id',$game_id)->where("status",1)->column("id");
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
        $sheetData = $spreadsheet->getActiveSheet(1)->toArray(null, true, true, true);
        $list = (new MapBoardContent())->whereIn('board_id',$mapBoardIds)->field("board_id,content_id")->select()->toArray();
        $keys = [];
        foreach ($list as $item){
            $keys[] = $item['board_id']."-".$item['content_id'];
        }
        unset($sheetData[1]);
        $mapBoardContent = [];
        Db::startTrans();
        foreach ($sheetData as $item){
            if(!in_array($item['A'],$mapBoardIds)||!in_array($item['B'],$mapContentIds)){
                continue;
            }
            if(in_array($item['A']."-".$item['B'],$keys)){
                continue;
            }
            $mapBoardContent[] = [
                'board_id' =>$item['A'],
                'content_id' =>$item['B'],
                'sort' =>$item['C'],
            ];
        }
        if(count($mapBoardContent)>0){
            (new MapBoardContent())->saveAll($mapBoardContent);
        }
        Db::commit();
        return $this->success("上传成功");
    }
}